<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\FreeCallHostOp;
use App\Http\Controllers\Controller;
use App\Model\HostPoolForNew;
use App\Model\Stat\StatDailyHostInfo;
use App\Model\User;
use App\Model\UserProfile;
use App\Util\AliyunUtil;
use App\Util\ComUtil;
use App\Util\InfoUtil;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;
use Illuminate\Support\MessageBag;

class FreeCallHostController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('官方运营女用户池');
            $content->description('');
            $content->body($this->grid());
        });
    }

    /**
     * Create interface
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('添加');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(HostPoolForNew::class, function (Grid $grid) {
            $where = [
                ['flag', 1]
            ];
            $grid->model()->where($where)->orderBy('id', 'desc');
            $grid->user_id('内部ID');
            $grid->userProfile()->user_profile_id('用户ID');
            $grid->userProfile()->avatar('头像')->display(function ($data) {
                return ComUtil::buidlImgaeHtml($data);
            });
            $grid->userProfile()->nick_name('用户昵称');
            $grid->userProfile()->updated_at('最后活跃时间')->display(function ($time) {
                return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
            });
            $grid->hostInfo()->income_total('总收入')->sortable();
            $grid->hostInfo()->income_video('视频收入')->sortable();
            $grid->hostInfo()->income_gift('礼物收入')->sortable();
            $grid->hostInfo()->income_msg('私信收入')->sortable();
            $dailyHostInfo = null;
            if (!request('cal_duration')) request()->merge(['cal_duration' => 1]);
            $offDay = intval(request('cal_duration'));
            $start = date('Y-m-d', strtotime("-{$offDay} day"));
            $end = date('Y-m-d', strtotime("-1 day"));
            $dailyHostInfo = StatDailyHostInfo::calAverage($start, $end);
            // }
            foreach (StatDailyHostInfo::SHOW_FIELDS as $field => $fieldName) {
                $grid->{$field}($fieldName)->display(function ($data) use ($field, $dailyHostInfo) {
                    $subfix = in_array($field, StatDailyHostInfo::RATE_FIELD) ? ' %' : '';
                    if (request('cal_duration')) {
                        $data = isset($dailyHostInfo[$this->user_id]) ? $dailyHostInfo[$this->user_id][$field] : '-';
                    } else {
                        $data = isset($this->dailyHostInfo[0]) ? $this->dailyHostInfo[0][$field] : '-';
                    }
                    if ($field == 'online_time' && $data != '-') $data = round($data / 3600, 2);
                    return $data . $subfix;
                })->sortable();
            }
            //禁用导出
            $grid->disableExport();
            //禁用行选择
            $grid->disableRowSelector();
            // $grid->disableActions();
            // $grid->disableCreateButton();

            $grid->filter(function ($filter) {
                $filter->expand();
                $filter->disableIdFilter();
                $filter->equal('userProfile.user_profile_id', '女用户用户ID');
                $filter->between('userProfile.created_at', '注册时间')->datetime();
                $filter->where(function ($query) {
                }, '计算周期', 'cal_duration')->select(StatDailyHostInfo::CAL_DURATION);
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();
                $actions->append(new FreeCallHostOp(
                    $actions->getKey(),
                    $actions->row,
                    'official_host/op'
                ));
            });
        });
    }

    function user_op()
    {
        $id = request('id');
        HostPoolForNew::where('id', $id)->limit(1)->update(['flag' => 0]);
        return ['ret' => 0, 'message' => '操作成功！'];
    }

    /**
     * 用户编辑
     * @return Form
     */
    protected function form()
    {
        return Admin::form(HostPoolForNew::class, function (Form $form) {
            $form->text('user_profile_id', '女用户ID')->placeholder('多个用户ID用逗号隔开');
            // $form->text('coin_setting', '设置免费通话补贴单价')->placeholder('xx金币/分钟');
            // $form->hidden('gender');
            //保存前回调
            $form->saving(function (Form $form) {
                $profileIds = explode(",", trim($form->user_profile_id));
                // echo json_encode($profileIds);
                $userIds = UserProfile::whereIn('user_profile_id', $profileIds)->pluck('user_id')->toArray();
                foreach ($userIds as $userId) {
                    HostPoolForNew::updateOrCreate([
                        'user_id' => $userId
                    ], [
                        'user_id' => $userId,
                        'gender' => 0,
                        'flag' => 1
                    ]);
                }
                return InfoUtil::adminSuc("绑定成功！" . json_encode($userIds));
            });
        });
    }
}
